<?php

namespace app\wechat\controller;

use app\enumerations\CustomerAccountLogTypeEnum;
use app\enumerations\FigureItemTypeEnum;
use EasyWeChat\Factory;
use think\Db;
use think\Exception;
use app\enumerations\FirstEnterCenterEnum;
use app\enumerations\PointDetailTypeEnum;
use app\enumerations\AccountDetailTypeEnum;

class OtherCenter extends Common {

    /**
     * 查看别人的小店
     * @return \think\response\Json
     */
    public function otherStoreCenter() {

        $currentCustomer = $this->request->currentCustomer;
        $customerId = $this->request->post("customerId");

        $customer = $this->customerService->findById($customerId);

        if (isNullOrEmpty($customer)) {
            return errorReturn('errorWechat.errorCustomerNotFound');
        }

        // 当天用户点赞且未领取的列表
        $likeReceiveList = $this->likeReceiveService
            ->getThisDayLikeReceiveListByMchCustomerId($customer['id']);

        // 场景图片列表
        $sceneList = $this->sceneService->getSceneListForApi();

        foreach ($sceneList as &$val) {
            $val['item_json'] = json_decode($val['item_json'], true);
        }

        // 门面图片列表
        $facadeList = $this->facadeService->getFacadeListForApi();

        // 元素图片列表
        $elementList = $this->elementService->getElementListForApi();

        // 人物列表
        $figureList = $this->figureService->getFigureListForApi();

        foreach ($figureList as $key=>$val) {

            // 头部
            $itemList['head'] = $this->figureItemService
                ->getFigureItemListByFigureIdAndIconType($val['id'],
                    FigureItemTypeEnum::getEnumValue(FigureItemTypeEnum::HEAD_CODE));
            //上半身
            $itemList['aboveTheWaist'] = $this->figureItemService
                ->getFigureItemListByFigureIdAndIconType($val['id'],
                    FigureItemTypeEnum::getEnumValue(FigureItemTypeEnum::ABOVETHEWAIST_CODE));
            // 下半身
            $itemList['lowerBody'] = $this->figureItemService
                ->getFigureItemListByFigureIdAndIconType($val['id'],
                    FigureItemTypeEnum::getEnumValue(FigureItemTypeEnum::LOWERBODY_CODE));
            // 人物其他
            $itemList['other'] = $this->figureItemService
                ->getFigureItemListByFigureIdAndIconType($val['id'],
                    FigureItemTypeEnum::getEnumValue(FigureItemTypeEnum::OTHER_CODE));

            $figureList[$key]['item_list'] = $itemList;
        }

        // 今天是否给这家点过赞
        $existLike = $this->likeService
            ->checkTodayExistLike($currentCustomer['id'], $customerId);

        // 今天是否已领取过这家店的积分
        $existLikeReceive = $this->likeReceiveService
            ->checkTodayExistLike($customerId, $currentCustomer['id']);

        // 用户信息
        $info['current_customer_id'] = $currentCustomer['id'];
        $info['customer_id'] = $customerId;
        $info['current_headimgurl'] = $currentCustomer['headimgurl'];
        $info['nickname'] = strExceedingLength($customer['nickname']);
        $info['headimgurl'] = $customer['headimgurl'];
        $info['history_point'] = $customer['history_point'];
        $info['total_point'] = $customer['total_point'];
        $info['sign'] = isNullOrEmpty($customer['sign'])
            ? config('constants.defaultSign') : $customer['sign'];
        $info['liked'] = isNullOrEmpty($existLike) ? false : true;
        $info['receive_liked'] = isNullOrEmpty($existLikeReceive) ? false : true;
        $info['receive_like_count'] = config('constants.receiveLikeCount');
        $info['first_enter_other_center'] = $currentCustomer['first_enter_other_center'];
        $info['newest_like_list'] = json_decode(
            $customer['newest_like_json'], true);
        $info['like_receive_list'] = $likeReceiveList;
        $info['home_json'] = json_decode($customer['home_json'], true);
        $info['renovation']['scene_list'] = $sceneList;
        $info['renovation']['facade_list'] = $facadeList;
        $info['renovation']['element_list'] = $elementList;
        $info['renovation']['figure_list'] = $figureList;

        // 无状态任务
        stateLessAsyncTask([
            "task_type" => "otherCenterFootPrint",
            "current_customer_id" => $currentCustomer["id"], // 访客用户
            "customer_id" => $customerId // 店主用户
        ]);

        return successReturn($info);

    }

    /**
     * 别人的个人中心
     * @return \think\response\Json
     */
    public function otherMyCenter() {

        $currentCustomer = $this->request->currentCustomer;
        $customerId = $this->request->post("customerId");

        $customer = $this->customerService->findById($customerId);

        if (isNullOrEmpty($customer)) {
            return errorReturn('errorWechat.errorCustomerNotFound');
        }

        $info['id'] = $customer['id'];
        $info['pid'] = $customer['yx_pid'];
        $info['nickname'] = strExceedingLength($customer['nickname']);
        $info['headimgurl'] = $customer['headimgurl'];
        $info['from_headimgurl'] = $currentCustomer['headimgurl'];
        $info['history_point'] = $customer['history_point'];
        $info['total_point'] = $customer['total_point'];
        $info['newest_like_list'] = json_decode(
            $customer['newest_like_json'], true);
        $info['history_profit'] = $customer['history_profit'];
        $info['total_assets'] = $customer['total_assets'];
        $info['history_point'] = $customer['history_point'];
        $info['total_point'] = $customer['total_point'];
        $info['background_image'] = $customer['background_image']
            .config('constants.ossProcessResizeH');
        $info['sign'] = $customer['sign'];

        return successReturn($info);

    }

    /**
     * 领取别人家的积分
     * @return \think\response\Json
     */
    public function receiveOtherPoint() {

        $currentCustomer = $this->request->currentCustomer;
        $customerId = $this->request->post("customerId");

        $customer = $this->customerService->findById($customerId);

        if (isNullOrEmpty($customer)) {
            return errorReturn('errorWechat.errorCustomerNotFound');
        }

        // 获取今天总共领了几家的积分
        $groupTodayLikeReceiveCount = $this->likeReceiveService
            ->groupTodayReceiveCount($currentCustomer['id']);

        if ($groupTodayLikeReceiveCount >=
                config("constants.todayReceiveCustomerCount")) {
            return errorReturn('errorWechat.errorTodayReceiveUpperLimit');
        }

        // 获取今天领取他家的积分总数
        $todayLikeReceiveCount = $this->likeReceiveService
            ->getTodayReceiveCount($customerId, $currentCustomer['id']);

        if ($todayLikeReceiveCount >= config('constants.receiveLikeCount')) {
            return errorReturn('errorWechat.errorTodayReceiveUpperLimit');
        }

        Db::startTrans();
        try {

            // 领取积分数据
            $likeReceiveData['like_customer_id'] = $customerId;
            $likeReceiveData['mch_customer_id'] = $currentCustomer['id'];
            $likeReceiveData['add_point'] = config("constants.likeReceiveAddPoint");
            $likeReceiveData['create_date'] = getCurrentDate();

            $saveLikeReceiveRes = $this->likeReceiveService->saveByData($likeReceiveData);

            // 会员数据
            $customerData['history_point'] =
                $currentCustomer['history_point']+$likeReceiveData['add_point'];
            $customerData['total_point'] =
                $currentCustomer['total_point']+$likeReceiveData['add_point'];

            $this->customerService->updateByIdAndData(
                $currentCustomer['id'], $customerData);

            // 积分流水数据
            $pointDetailData['point'] = $likeReceiveData['add_point'];
            $pointDetailData['customer_id'] = $currentCustomer['id'];
            $pointDetailData['type'] = PointDetailTypeEnum::getEnumValue(PointDetailTypeEnum::LIKERECEIVE_CODE);
            $pointDetailData['refer_id'] = $saveLikeReceiveRes['id'];
            $pointDetailData['refer_customer_id'] = $likeReceiveData['like_customer_id'];
            $pointDetailData['refer_customer_nickname'] = $customer['nickname'];
            $pointDetailData['refer_customer_headimgurl'] = $customer['headimgurl'];

            $this->pointDetailService->saveByData($pointDetailData);

            // 点赞获得积分LOG
            $customerAccountLogData['customer_id'] = $currentCustomer['id'];
            $customerAccountLogData['refer_customer_id'] = $likeReceiveData['like_customer_id'];
            $customerAccountLogData['type'] = CustomerAccountLogTypeEnum::getEnumValue(CustomerAccountLogTypeEnum::LIKERECEIVE_CODE);
            $customerAccountLogData['value'] = $likeReceiveData['add_point'];
            $customerAccountLogData['refer_id'] = $saveLikeReceiveRes['id'];

            $this->customerAccountLogService->saveByData($customerAccountLogData);

            Db::commit();

        } catch(\PDOException $e) {

            Db::rollback();

            return errorReturn('errorWechat.errorService');

        }

        return successReturn();

    }

    /**
     * 别人的累计消费排行榜
     * @return \think\response\Json
     */
    public function otherConsumeRankingList() {

        $currentCustomer = $this->request->currentCustomer;
        $customerId = $this->request->post("customerId");
        $pageNum = $this->request->post("pageNum");
        $pageSize = $this->request->post("pageSize");

        $customer = $this->customerService->findById($customerId);

        if (isNullOrEmpty($customer)) {
            return errorReturn('errorWechat.errorCustomerNotFound');
        }

        $list = $this->consumeService
            ->getConsumeRankingListForPage(
                $customerId, $pageNum, $pageSize);

        $returnData['info']['headimgurl'] = $currentCustomer['headimgurl'];
        $returnData['info']['background_image'] = $currentCustomer['background_image']
            .config('constants.ossProcessResizeH');
        $returnData['list'] = $list;

        return successReturn($returnData);

    }

    /**
     * 别人的累计贡献积分排行榜
     * @return \think\response\Json
     */
    public function otherPointRankingList() {

        $currentCustomer = $this->request->currentCustomer;
        $customerId = $this->request->post("customerId");
        $pageNum = $this->request->post("pageNum");
        $pageSize = $this->request->post("pageSize");

        $customer = $this->customerService->findById($customerId);

        if (isNullOrEmpty($customer)) {
            return errorReturn('errorWechat.errorCustomerNotFound');
        }

        $list = $this->likeService
            ->getPointRankingListForPage(
                $customerId, $pageNum, $pageSize);

        $returnData['info']['headimgurl'] = $currentCustomer['headimgurl'];
        $returnData['list'] = $list;

        return successReturn($returnData);

    }

}